package handlers

import (
	"fmt"
	"net/http"
	"strconv"
	"time"

	"miracle-recorder/internal/models"
	"miracle-recorder/internal/services"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type LivestreamHandler struct {
	livestreamService *services.LivestreamService
}

func NewLivestreamHandler(livestreamService *services.LivestreamService) *LivestreamHandler {
	return &LivestreamHandler{livestreamService: livestreamService}
}

func (h *LivestreamHandler) ListLivestreams(c *gin.Context) {
	limitStr := c.DefaultQuery("limit", "20")
	offsetStr := c.DefaultQuery("offset", "0")
	status := c.DefaultQuery("status", "live")

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit <= 0 {
		limit = 20
	}

	offset, err := strconv.Atoi(offsetStr)
	if err != nil || offset < 0 {
		offset = 0
	}

	livestreams, err := h.livestreamService.ListLivestreams(limit, offset, status)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get livestreams"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"livestreams": livestreams,
		"pagination": gin.H{
			"limit":  limit,
			"offset": offset,
		},
	})
}

func (h *LivestreamHandler) GetLivestream(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid livestream ID"})
		return
	}

	livestream, err := h.livestreamService.GetLivestream(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Livestream not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"livestream": livestream})
}

func (h *LivestreamHandler) CreateLivestream(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	var req models.CreateLivestreamRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 生成推流URL
	streamKey := uuid.New().String()
	rtmpURL := fmt.Sprintf("rtmp://localhost:1935/live/%s", streamKey)
	hlsURL := fmt.Sprintf("http://localhost:8080/hls/%s.m3u8", streamKey)

	livestream := &models.Livestream{
		Title:       req.Title,
		Description: req.Description,
		TopicID:     req.TopicID,
		StreamerID:  userID.(int),
		RTMPURL:     rtmpURL,
		HLSURL:      hlsURL,
		Status:      "pending",
		ViewerCount: 0,
		MaxViewers:  1000,
		IsRecording: true,
		Tags:        req.Tags,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}

	if err := h.livestreamService.CreateLivestream(livestream); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create livestream"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"message":    "Livestream created successfully",
		"livestream": livestream,
		"stream_key": streamKey,
	})
}

func (h *LivestreamHandler) StartLivestream(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid livestream ID"})
		return
	}

	livestream, err := h.livestreamService.GetLivestream(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Livestream not found"})
		return
	}

	// 检查权限
	if livestream.StreamerID != userID.(int) {
		c.JSON(http.StatusForbidden, gin.H{"error": "Permission denied"})
		return
	}

	if err := h.livestreamService.StartLivestream(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to start livestream"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Livestream started successfully"})
}

func (h *LivestreamHandler) StopLivestream(c *gin.Context) {
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
		return
	}

	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid livestream ID"})
		return
	}

	livestream, err := h.livestreamService.GetLivestream(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Livestream not found"})
		return
	}

	// 检查权限
	if livestream.StreamerID != userID.(int) {
		c.JSON(http.StatusForbidden, gin.H{"error": "Permission denied"})
		return
	}

	if err := h.livestreamService.StopLivestream(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to stop livestream"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Livestream stopped successfully"})
}

type AIHandler struct {
	aiService *services.AIService
}

func NewAIHandler(aiService *services.AIService) *AIHandler {
	return &AIHandler{aiService: aiService}
}

func (h *AIHandler) SummarizeContent(c *gin.Context) {
	var req models.AISummarizeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	summary, err := h.aiService.SummarizeContent(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to summarize content"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"summary": *summary,
	})
}

func (h *AIHandler) GenerateSolution(c *gin.Context) {
	var req models.GenerateSolutionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	solution, err := h.aiService.GenerateSolution(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate solution"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"solution": *solution,
	})
}

type UploadHandler struct {
	uploadService *services.UploadService
}

func NewUploadHandler(uploadService *services.UploadService) *UploadHandler {
	return &UploadHandler{uploadService: uploadService}
}

func (h *UploadHandler) UploadFile(c *gin.Context) {
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No file uploaded"})
		return
	}
	defer file.Close()

	// 检查文件大小
	if header.Size > 100*1024*1024 { // 100MB
		c.JSON(http.StatusBadRequest, gin.H{"error": "File too large"})
		return
	}

	allowedTypes := []string{".jpg", ".jpeg", ".png", ".gif", ".mp4", ".mov", ".mp3", ".wav", ".pdf", ".doc", ".docx"}

	fileURL, err := h.uploadService.UploadFile(file, header, allowedTypes)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to upload file"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "File uploaded successfully",
		"url":     *fileURL,
		"type":    h.uploadService.GetFileType(header.Filename),
		"size":    header.Size,
	})
}

func (h *UploadHandler) DownloadFile(c *gin.Context) {
	filename := c.Param("filename")
	filepath := h.uploadService.GetFilePath(filename)

	// 检查文件是否存在
	if _, err := os.Stat(filepath); os.IsNotExist(err) {
		c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
		return
	}

	c.File(filepath)
}